package com.sychip.fhc.app.drawer.screen

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.BluetoothSearching
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.fhc.base.noStyle
import com.fhc.base.parseBold
import com.fhc.view.CircleTextView
import com.fhc.view.list.swip.SwipeAction
import com.fhc.view.list.swip.SwipeableActionsBox
import com.fhc.view.list.swip.SwipeableActionsState
import com.fhc.view.list.swip.rememberSwipeableActionsState
import com.fhc.view.utils.Hint
import com.fhc.view.utils.ListShimmerView
import com.sychip.fhc.app.data.source.dto.BleDeviceDto
import com.sychip.fhc.app.drawer.screen.PullListViewModel.UiTestState
import com.sychip.fhc.app.todo.R
import com.sychip.fhc.lib.base.FhcTopAppBar
import kotlinx.coroutines.launch
import timber.log.Timber
import kotlin.math.roundToInt


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PullListScreen(viewModel: PullListViewModel = hiltViewModel(), onNavigationClick: () -> Unit ={}) {
    val uiTestState by viewModel.testFlow.collectAsStateWithLifecycle()
    val pullRefreshState = rememberPullToRefreshState()
    val scope =  rememberCoroutineScope()
    val deviceItem: @Composable (BleDeviceDto) -> Unit = {
        UserListItem(it.name , it.devId){
            Text(modifier = Modifier.widthIn(max = 120.dp), text = "${it.lastConnected}",  style = MaterialTheme.typography.bodySmall )
        }
    }

    Scaffold(
        topBar = {
            FhcTopAppBar(
                title =  R.string.app_name,
                navigationIcon = {
                    IconButton(onClick = onNavigationClick) {
                        Icon(Icons.Filled.Menu, stringResource(id = R.string.open_drawer))
                    }
                },
                actions ={}
            )
        },
    ) { innerPadding ->
       PullToRefreshBox(
            modifier = Modifier.padding(top = innerPadding.calculateTopPadding()).fillMaxSize(),
            isRefreshing = uiTestState is UiTestState.Loading,
            onRefresh = {
                viewModel.reloadTestData()
                scope.launch {
                    pullRefreshState.animateToHidden()
                }
            },
            state = pullRefreshState,
            content = {
                UsersListView(
                    viewModel = viewModel,
                    uiTestState = uiTestState,
                    modifier = Modifier.fillMaxSize().background(Color.Gray),
                    userItem = deviceItem
                )
            }
        )
    }
}

@Composable
fun UsersListView(
    viewModel: PullListViewModel,
    uiTestState: UiTestState,
    modifier: Modifier = Modifier,
    userItem: @Composable (BleDeviceDto) -> Unit = {
        UserListItem(it.name, it.devId)
    },
) {
    if(uiTestState is UiTestState.Success){
        if (!uiTestState.data.isEmpty()) {
            SwipeLazyColumn(viewModel,uiTestState, userItem)
//            LazyColumn(
//                modifier = modifier.background(Color.Blue.copy(alpha = 0.3f)),
//                contentPadding = PaddingValues(horizontal = 8.dp, vertical = 16.dp)
//            ) {
//                items(count = uiTestState.data.size, key = {uiTestState.data[it].devId}) {
//                    ClickableUserItem(uiTestState.data[it], userItem)
//                    // 添加分隔线
//                    HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))
//                }
//            }
        } else {
            Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
                LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp) ) { }
                ListEmptyView(modifier = Modifier.fillMaxSize(), state = uiTestState, onRefresh = {
                    viewModel.reloadTestData()
                })
            }
        }
    }else if(uiTestState is UiTestState.Loading){
        Column{
            ListShimmerView()
            ListShimmerView()
            ListShimmerView()
        }
    }else{
        ListEmptyView(modifier, uiTestState, onRefresh = {
            viewModel.reloadTestData()
        })
    }

}




@Preview(showBackground = true)
@Composable
fun ListEmptyView( modifier : Modifier = Modifier, state: UiTestState = UiTestState.Loading, onRefresh: () -> Unit = {}) {
    Box(modifier = modifier.fillMaxSize(),
        contentAlignment = Alignment.Center){
        Column(
            modifier = modifier.align(Alignment.Center),
            verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {

            Image(
                painter = rememberVectorPainter(image = Icons.AutoMirrored.Filled.BluetoothSearching),
                contentDescription = null,
                modifier = Modifier.size(80.dp),
                colorFilter = ColorFilter.tint(colorScheme.onBackground.copy(alpha = 0.6f)),
            )
            Text(text = stringResource(id = R.string.wsn_no_device_data_title), color  =colorScheme.primary, fontWeight = FontWeight.ExtraBold)
            Hint(text = stringResource(id = R.string.wsn_no_device_data_info).noStyle(), textAlign = TextAlign.Center)
            when (state) {
                is UiTestState.Loading ->  {  }
                is UiTestState.Success -> {
                    if (state.data.isEmpty()) {
                        Hint(text = "state.data.isEmpty()".parseBold(), textAlign = TextAlign.Center)
                        Button(onClick = {
                            onRefresh()
                            Timber.i("   >>>>>  Button   onClick")
                        }) {
                            Text(text = "Success isEmpty --"+stringResource(id = R.string.refresh))
                        }
                    }
                }
                is UiTestState.Error -> {
                    Hint(text = stringResource(id = com.fhc.ble.R.string.no_device_guide_info).parseBold(), textAlign = TextAlign.Center)
                    Button(onClick = {
                        onRefresh()
                        Timber.i("   >>>>>  Button   onClick")
                    }) {
                        Text(text = "Error --"+stringResource(id = com.fhc.ble.R.string.scanner_error))
                    }
                }
                is UiTestState.Null -> {
                    Hint(text = stringResource(id = com.fhc.ble.R.string.no_device_guide_info).parseBold(), textAlign = TextAlign.Center)
                    Button(onClick = {
                        onRefresh()
                        Timber.i("   >>>>>  Button   onClick")
                    }) {
                        Text(text = "Null --"+stringResource(id = R.string.refresh))
                    }
                }
            }
        }
    }

}


//fun LazyListScope.userListItems(
//    uiTestState: UiTestState.Success,
//    userView: @Composable (User) -> Unit,
//) {
//        item {
//            Text(
//                text = stringResource(id = R.string.bonded_devices),
//                style = MaterialTheme.typography.titleSmall,
//                modifier = Modifier.padding(start = 8.dp, bottom = 8.dp)
//            )
//        }
//        items(uiTestState.data.size) {
//            ClickableUserItem(uiTestState.data[it], userView)
//            // 添加分隔线
//            HorizontalDivider(modifier = Modifier.padding(horizontal = 16.dp))
//        }
//
//}

@Composable
fun UserListItem(
    name: String,
    mac: String,
    modifier: Modifier = Modifier,
    extras: @Composable () -> Unit = {},
) {
    Row(
        modifier = modifier,
        verticalAlignment = Alignment.CenterVertically)
    {

        Spacer(modifier = Modifier.width(16.dp))

        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
        ) {
            name.takeIf { it.isNotEmpty() }?.let { name ->
                Text( text = name, style = MaterialTheme.typography.titleMedium )
            } ?: Text(
                text = stringResource(id = com.fhc.ble.R.string.device_no_name),
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.alpha(0.7f)
            )
            Text( text = "Mac:$mac",  style = MaterialTheme.typography.bodyMedium )
        }

        extras()
    }
}


@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ClickableUserItem(
    user: BleDeviceDto,
    userView: @Composable ((BleDeviceDto) -> Unit),
) {
    var isMenuExpanded by remember { mutableStateOf(false) }
//    https://www.jb51.net/article/267786.htm

    var boxOffset: Offset by remember { mutableStateOf(Offset(0f,0f)) }
    var x by remember { mutableStateOf(0.dp) }
    var y by remember { mutableStateOf(0.dp) }
    Box(modifier = Modifier
        .combinedClickable(
            onClick = {
                Timber.i("   onClick  222 >>>>>>>>>>>>>>>>>>>>>>>>> ${user.devId}")
            },
            onLongClick = {
                isMenuExpanded = true
                Timber.i("   onLongClick  222 >>>>>>>>>>>>>>>>>>>>>>>>> ${user.name}")
            },
        )
        .pointerInput(Unit) {
            awaitEachGesture {
                awaitFirstDown().also {
                    boxOffset = it.position
                }
            }
        }
        .clip(RoundedCornerShape(10.dp))
        .padding(8.dp)
    ) {
        userView(user)
        Box(modifier = Modifier.offset {
            IntOffset(
                boxOffset.x.roundToInt(),
                boxOffset.y.roundToInt()
            )
        } ) {
            DropdownMenu(
                modifier = Modifier.offset(x, y),
                expanded = isMenuExpanded,
                onDismissRequest = { isMenuExpanded = false }
            ) {
                val items = listOf("分享", "收藏", "删除")
                items.forEachIndexed { index, item ->
                    DropdownMenuItem(
                        onClick = {
                            Timber.i("   onClick  222 >>>>>>>>>>>>>>>>>>>>>>>>> ")
                            isMenuExpanded = false
                        },
                        text = { Text(text = item) },
                    )
                }
            }
        }
    }
}




@Composable
private fun SwipeLazyColumn(
    viewModel: PullListViewModel,
    uiTestState: UiTestState.Success,
    userView: @Composable ((BleDeviceDto) -> Unit),
) {


    val scope = rememberCoroutineScope()
    var stateDragOld: SwipeableActionsState? = null
    LazyColumn(
        modifier = Modifier
            .fillMaxSize()
            .padding(top = 50.dp),
    ) {
        //items务必添加key，否则会造成显示错乱
        itemsIndexed(uiTestState.data, key = { index, item -> item.devId }) { index, item ->
            //index和item都是最原始的数据，一旦onDelete和onChange过，index和item就都不准了，因此根据item的id作为唯一标识查找
            val delete = SwipeAction(
                icon = rememberVectorPainter(Icons.Default.Delete),
                background = Color.Red,
                onClick = {

                    viewModel.deleteData(index, item.devId)
//                    data.remove(data.find { it.devId == item.devId })
                          },
            )
            val change = SwipeAction(
                icon = { Text("add") },
                background = Color.Green,
                onClick = {
                    viewModel.addData()

//                    data[data.indexOf(data.find { it.devId == item.devId })] =
//                        item.copy(mac = "Item has change: ${item.devId}")
                },
                resetAfterClick = true,
                iconSize = 20.dp
            )
            val change2 = SwipeAction(
                icon = rememberVectorPainter(Icons.Default.Add),
                background = Color.Blue,
                onClick = {
                    viewModel.addData()
//                    data[data.indexOf(data.find { it.devId == item.devId })] =
//                        item.copy(mac = "Item has change: ${item.devId}")
                },
            )
            val state = rememberSwipeableActionsState()
            SwipeableActionsBox(
                state = state,
                startActions = listOf(change),
                endActions = listOf(delete, change2),
                swipeThreshold = 80.dp,
                onDragStopped = {it->
                    stateDragOld = it
                },
                onDragStarted = {it->
//                    stateDragOld?.offsetState?.value = 0f   //关闭swipe，没有动画
                    scope.launch{
                        if(stateDragOld != it) {
//                            stateDragOld?.handleReset()
                        }
                    }
                }
            ) {
                Timber.i("   SwipeLazyColumn  222 >>>>>>>>>>>>>>>>>>>>>>>>> %s   %s",index, state.offsetState.floatValue)
                Box(modifier = Modifier
                    .clip(RoundedCornerShape(10.dp))
                    .clickable { }
                    .padding(8.dp)
                ) {
                    userView(uiTestState.data[index])
                }
            }
            HorizontalDivider(modifier = Modifier.padding(horizontal = 6.dp))
        }
    }

}